<template>
  <div class="main">
    <MyHeader :searchForm="searchForm" @search="handleSearch"></MyHeader>
    <el-card class="bottom">
      <div class="table-overview">
        <div class="left">
          <span>活动列表</span>
          <span class="total"
            >共
            <span> {{ pagination.total }}</span>
            条记录
          </span>

          <el-button
            class="delete-btn"
            type="danger"
            @click="handleDeleteList"
            v-if="computedSelectedTable.length >= 2"
            >删除{{ computedSelectedTable.length }}条</el-button
          >
        </div>
        <div class="right">
          <el-button type="primary" @click="exportSelected">导出选中</el-button>
          <el-button type="primary" @click="showExportAllDialog"
            >导出全部</el-button
          >
          <el-button type="primary" @click="showAddDialog">新增</el-button>
        </div>
      </div>
      <ActivityTable
        :tableData="tableData"
        :selectedTable="selectedTable"
        :pagination="pagination"
        @edit="showEditDialog"
        @delete="showDeleteDialog"
        @preview="showPreviewDialog"
        @currentChange="handleCurrentChange"
        @selectionChange="handleSelectionChange"
        @updateCell="handleUpdateCell"
      >
      </ActivityTable>

      <AddDialog
        :addDialogVisible="addDialogVisible"
        @closeAddDialog="handleCloseAddDialog"
        @confirm="handleConfirmAdd"
      ></AddDialog>

      <EditDialog
        :editForm="editForm"
        :editDialogVisible="editDialogVisible"
        @closeEditDialog="handleCloseEditDialog"
        @confirm="handleConfirmEdit"
      >
      </EditDialog>

      <DeleteDialog
        :deleteDialogVisible="deleteDialogVisible"
        @closeDeleteDialog="handleCloseDeleteDialog"
        @confirm="handleDelete"
      >
        确认删除这行数据以及附件吗？
      </DeleteDialog>

      <PreviewDialog
        :previewForm="previewForm"
        :previewDialogVisible="previewDialogVisible"
        @closePreviewDialog="handleClosePreviewDialog"
      >
      </PreviewDialog>

      <ExportDialog
        :exportAllDialogVisible="exportAllDialogVisible"
        :tableData="exportTableData"
        @closeExportAllDialog="handleCloseExportAllDialog"
      ></ExportDialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import ActivityTable from "./components/ActivityTable.vue";
import DeleteDialog from "@/components/DeleteDialog.vue";
import AddDialog from "./components/AddDialog.vue";
import EditDialog from "./components/EditDialog.vue";
import ExportDialog from "./components/ExportDialog.vue";
import PreviewDialog from "@/components/PreviewDialog.vue";
import MyHeader from "./components/MyHeader.vue";

import { utils, writeFile } from "xlsx";
import { computed, reactive, toRefs } from "vue";
import { ElLoading, ElMessage } from "element-plus";
import lodash from "lodash";
import { useStore } from "vuex";

import { ActivityTableHeads } from "@/data/tableConfig.ts";
import { activityTableMap } from "@/data/tableMap.ts";

import {
  getList,
  deleteActivity,
  deleteActivityList,
  updateActivity,
} from "@/api/activity/index.ts";
import { baseURL } from "@/api/base.ts";
import { getAll } from "@/api/activity";

import { formatDate } from "@/utils/formatDate";

const tableData: IObj = reactive([]);

const state = reactive({
  addDialogVisible: false,
  deleteDialogVisible: false,
  editDialogVisible: false,
  previewDialogVisible: false,
  exportAllDialogVisible: false,
  editForm: {},
  previewForm: {},
});

const {
  addDialogVisible,
  deleteDialogVisible,
  editDialogVisible,
  previewDialogVisible,
  exportAllDialogVisible,
  editForm,
  previewForm,
} = toRefs(state);

const pagination = reactive({
  // 当前页
  currentPage: 1,

  // 一页数据条数
  pageSize: 10,

  // 总数据条数
  total: 0,
});

const handleCurrentChange = (page: number) => {
  console.log(pagination);
  initTableData();
};

async function getDataList(
  page: number,
  limit: number,
  condition?: {
    activityName?: string;
    organization?: number;
    activityTime?: string;
  }
) {
  const { data: res } = await getList(page, limit, {
    ...condition,
  });
  if (res.code === 200) {
    pagination.total = res.data.total;
    // 清空数组
    tableData.splice(0, tableData.length);

    for (const item of res.data.records) {

      const obj = {
        rowId: item._id,
        activityName: item.name,
        activityIntro: item.intro,
        organization: item.organization,
        activityTime: formatDate(new Date(item.time)),
        photos: []
      };

      item.photos.forEach((pic: IObj) => {
        let tempPic = pic;
        tempPic.url = `/pic${pic.url}`;

        obj.photos.push(pic as never);
      });

      tableData.push(obj);
    }

    console.log(tableData);
  }
}

const searchForm: IObj = reactive({
  activityName: "",
  organization: "",
  activityTime: "",
});
const handleSearch = () => {
  const obj: IObj = {};

  const map: IObj = {
    activityName: "name",
    activityTime: "time",
    organization: "organization",
  };

  for (const item in searchForm) {
    if (searchForm[item] != "") {
      obj[map[item]] = searchForm[item];
    }
  }

  // console.log(obj);

  getDataList(pagination.currentPage, pagination.pageSize, obj);
};

function initTableData() {
  handleSearch();
}

initTableData();

// 事件

const showAddDialog = () => {
  addDialogVisible.value = true;
};

const handleCloseAddDialog = () => {
  addDialogVisible.value = false;
};

const handleConfirmAdd = () => {
  ElMessage({
    message: "新增成功",
    type: "success",
  });

  initTableData();
};

const showEditDialog = (row: any) => {
  editDialogVisible.value = true;
  editForm.value = lodash.cloneDeep(row);

  (editForm.value as IObj).addPhotos = [];
  (editForm.value as IObj).deleteIds = [];
};

const handleCloseEditDialog = () => {
  editDialogVisible.value = false;
};

const handleConfirmEdit = () => {
  handleCloseEditDialog();

  ElMessage({
    message: "修改成功",
    type: "success",
  });

  initTableData();
};

const handleUpdateCell = async (index: number, attribute: string) => {
  const { data } = await updateActivity({
    _id: tableData[index].rowId,
    name: tableData[index].activityName,
    intro: tableData[index].activityIntro,
    time: tableData[index].activityTime,
    organization: tableData[index].organization,
  });

  if (data.code === 200) {
    initTableData();

    ElMessage({
      message: "更新成功",
      type: "success",
    });
  }
};

const loading: IObj = reactive({});

// 删除
let deleteId: number;
const showDeleteDialog = (row: any) => {
  deleteId = row.rowId;
  deleteDialogVisible.value = true;
};

const handleCloseDeleteDialog = () => {
  deleteDialogVisible.value = false;
};

const handleDelete = async () => {
  const { data } = await deleteActivity(deleteId);

  if (data.code === 200) {
    handleCloseDeleteDialog();

    if (selectedTable[pagination.currentPage] !== undefined) {
      selectedTable[pagination.currentPage] = selectedTable[
        pagination.currentPage
      ].filter((item: IObj) => item.rowId != deleteId);
    }

    initTableData();

    ElMessage({
      message: "删除成功",
      type: "success",
    });
  }
};

const handleDeleteList = async () => {
  const idList = [];

  for (const item of computedSelectedTable.value) {
    idList.push(item.rowId);
  }

  console.log(idList);

  const { data } = await deleteActivityList(idList);

  if (data.code === 200) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });

    for (const deleteId of idList) {
      const page = Math.ceil(pagination.total / pagination.pageSize);

      for (let i = 1; i <= page; i++)
      if (selectedTable[i] !== undefined) {
        selectedTable[i] = selectedTable[i].filter((item: IObj) => item.rowId != deleteId);
      }
    }

    initTableData();
  }
};

const showPreviewDialog = (row: any) => {
  previewDialogVisible.value = true;
  previewForm.value = row;
};

const handleClosePreviewDialog = () => {
  previewDialogVisible.value = false;
};

// 导出
const exportTableData: IObj[] = reactive([]);

const showExportAllDialog = async () => {
  const { data: res } = await getAll();
  if (res.code === 200) {
    // 清空数组
    exportTableData.splice(0, exportTableData.length);

    for (const item of res.data) {
      const obj = {
        rowId: item._id,
        activityName: item.name,
        activityIntro: item.intro,
        organization: item.organization,
        activityTime: formatDate(new Date(item.time))
      };

      exportTableData.push(obj);
    }
  }

  exportAllDialogVisible.value = true;
};

const handleCloseExportAllDialog = () => {
  exportAllDialogVisible.value = false;
};

let selectedTable: IObj = reactive({});

const computedSelectedTable = computed(() => {
  const result = [];

  for (const item in selectedTable) {
    if (selectedTable[item].length != 0) {
      result.push(...selectedTable[item]);
    }
  }
  return result;
});
const handleSelectionChange = (selection: IOrganizationTable[]) => {
  selectedTable[pagination.currentPage] = lodash.cloneDeep(selection);
};

const exportSelected = () => {
  if (computedSelectedTable.value.length <= 0) {
    return;
  }

  exportTableData.splice(0, exportTableData.length);

  for (const row of computedSelectedTable.value) {

    exportTableData.push(row);
  }

  exportAllDialogVisible.value = true;
};
</script>

<style lang="less" scoped>
.bottom {
  margin-top: 28px;

  .table-overview {
    display: flex;
    justify-content: space-between;
    height: 60px;
    line-height: 30px;

    .left {
      .total {
        margin-left: 50px;
      }

      .delete-btn {
        margin-left: 20px;
      }
    }
  }
}
</style>
